package com.warrior.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.warrior.Exception.ProjectException;
import com.warrior.configer.ConfigHelper;
import com.warrior.entity.*;
import com.warrior.service.*;
import com.warrior.util.CModelAndView;
import com.warrior.util.CommonUtils;
import com.warrior.util.ServerResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 活动controller层
 * Created by Shawn on 2017/3/27.
 */
@Controller
@RequestMapping("/activity")
public class ActivityController {

    private static final Logger logger = LogManager.getLogger(ActivityController.class.getName());

    @Autowired
    private ActivityService activityService;

    @Autowired
    private TeamService teamService;

    @Autowired
    private UserService userService;

    @Autowired
    private MatchDetailsService matchDetailsService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private TeamTools teamTools;

    private static final String RankingRulesId = ConfigHelper.getConfig().getString("rules.ranking");

    private static final String SeriesRulesId = ConfigHelper.getConfig().getString("rules.series");


    /**
     * 活动介绍
     *
     * @param id       活动id
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/activity_introduce", method = RequestMethod.GET)
    public ModelAndView findActivityContents(String id, HttpServletRequest request, HttpServletResponse response) {
        if (logger.isDebugEnabled()) {
            logger.debug("findActivityContents(String id={}, HttpServletRequest request={}, HttpServletResponse response={}) - start", id, request, response); //$NON-NLS-1$
        }

        ModelAndView mv = new CModelAndView("/warrior/activity/activity_introduce", request, response);
        List<ActivityContentEntity> activityContentEntities = this.activityService.findAllContentByActivityId(id);
        mv.addObject("activityContentEntities", activityContentEntities);

        ActivityEntity activityEntity = this.activityService.findActivityById(id);
        mv.addObject("activityEntity", activityEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("findActivityContents(String, HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return mv;
    }


    /**
     * 显示活动列表
     *
     * @param size      每页数据量
     * @param page      页码
     * @param orderType 排序类型 desc/asc
     * @param request   request
     * @param response  response
     * @return ModelAndView
     */
    @RequestMapping(value = "/activity_list", method = RequestMethod.GET)
    public ModelAndView listAllActivity(String size, String page, String orderType, HttpServletRequest request, HttpServletResponse response) {
        if (logger.isDebugEnabled()) {
            logger.debug("listAllActivity(String size={}, String page={},String orderType={}, HttpServletRequest request={}, HttpServletResponse response={}) - start", size, page, orderType, request, response); //$NON-NLS-1$
        }

        ModelAndView mv = new CModelAndView("/warrior/activity/game_list", request, response);
        //积分赛内容
        Page<ActivityEntity> activityEntities = this.activityService.listActivityByActivityType(CommonUtils.String2Int(size), CommonUtils.String2Int(page), 0, orderType);
        mv.addObject("activityEntitiesRanking", activityEntities);
        //系列赛内容
        Page<ActivityEntity> activityEntities2 = this.activityService.listActivityByActivityType(CommonUtils.String2Int(size), CommonUtils.String2Int(page), 1, orderType);
        mv.addObject("activityEntitiesSeries", activityEntities2);
        //获取积分赛规则
        ArticleEntity rankingArticle = this.articleService.findArticleById(RankingRulesId);
        mv.addObject("rankingArticle", rankingArticle);
        //获取系列赛规则
        ArticleEntity seriesArticle = this.articleService.findArticleById(SeriesRulesId);
        mv.addObject("seriesArticle", seriesArticle);

        if (logger.isDebugEnabled()) {
            logger.debug("listAllActivity(String, String, String, String, HttpServletRequest, HttpServletResponse) - end"); //$NON-NLS-1$
        }
        return mv;
    }


    /**
     * 报名中的活动
     *
     * @param id       活动id
     * @param request  request
     * @param response response
     * @return ModelAndView
     * @throws ProjectException 异常处理
     */
    @RequestMapping(value = "/activity_details", method = RequestMethod.GET)
    public ModelAndView showActivityDetails(String id, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new CModelAndView("/warrior/team/team_apply_1", request, response);
        //活动详情
        ActivityEntity activityEntity = this.activityService.findActivityById(id);
        mv.addObject("activity", activityEntity);

        //获取参赛队伍数量
        int teamNum = this.teamService.getAttendTeamNum(id);
        mv.addObject("teamNum", teamNum);

        //获取参赛队伍信息
        List<TeamEntity> teamEntities = this.teamService.findTeamsInfoByActivityId(id);
        String userId = (String) request.getSession().getAttribute("userId");
        //得到用户信息
        UserEntity userEntity = this.userService.findUserById(userId);
        if (null != userEntity) {
            mv.addObject("userId", userId);
            mv.addObject("teamEntities", teamEntities);
            //查看该用户是否是队长
            boolean flag = false;
            if (1 == userEntity.getIsCaption()) {
                flag = true;
            }
            mv.addObject("isCaption", flag);
            List<UserEntity> list = new ArrayList<>();
            for (TeamEntity tm : teamEntities) {
                list.add(this.userService.findUserById(tm.getCaptionId()));
            }
            if (list.contains(userEntity)) {
                //队伍已报名
                mv.addObject("is_attend", true);
            }
            if (userEntity.getTeamEntity() == null) {
                mv.addObject("errorMsg", "用户暂时没有队伍");
            }else{
                TeamEntity teamEntity = this.teamService.findTeamByTeamId(userEntity.getTeamEntity().getId());
                mv.addObject("ownTeam", teamEntity);
            }
        } else {
            mv.addObject("errorMsg", "用户不存在");
        }

        return mv;
    }


    /**
     * 根据活动id拿到准备活动的信息
     *
     * @param activityId 活动id
     * @param request    req
     * @param response   res
     * @return ModelAndView
     * @throws ProjectException 未找到队伍异常
     */
    @RequestMapping(value = "/activity_details_prepare", method = RequestMethod.GET)
    public ModelAndView findActivityPrepareDetails(String activityId, HttpServletRequest request, HttpServletResponse response){
        ModelAndView mv = new CModelAndView("/warrior/activity/game_view", request, response);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        mv.addObject("activity", activityEntity);
        mv.addObject("teamTools",teamTools);
        int teamNum = this.teamService.getAttendTeamNum(activityId);
        mv.addObject("teamNum",teamNum);
        List<MatchDetailsEntity> matchEntities = null;
        try {
            matchEntities = this.matchDetailsService.findMatchDetailsByActivityId(activityId);
        } catch (ProjectException e) {
            e.printStackTrace();
        }
        mv.addObject("matchDetails", matchEntities);
        return mv;
    }


    /**
     * 参加活动
     *
     * @param request    request
     * @param response   response
     * @param activityId 活动id
     * @param teamId     队伍id
     * @return ModelAndView
     */
    @RequestMapping(value = "/attendActivity", method = RequestMethod.GET)
    public ModelAndView attendActivity(HttpServletRequest request, HttpServletResponse response, String activityId, String teamId,String userId) {
        ModelAndView mv = new CModelAndView("/warrior/team/team_apply_2", request, response);

        try {
            this.teamService.attendNewActive(teamId, activityId, userId);
        } catch (ProjectException e) {
            mv = new CModelAndView("/500", request, response);
            mv.addObject("errorMsg", e.getMessage());
            return mv;
        }
        mv.addObject("activityId", activityId);
        mv.addObject("teamId",teamId);
        return mv;
    }


    @RequestMapping("/team_apply_2")
    public ModelAndView ValidateTicket(HttpServletRequest request, HttpServletResponse response, String activityId) {
        ModelAndView mv = new CModelAndView("/warrior/team/team_apply_2", request, response);
        mv.addObject("activityId", activityId);
        return mv;
    }


    /**
     * 先伪装验证
     *
     * @param code
     * @return
     * @throws JsonProcessingException
     */
    @RequestMapping(value = "/validate_ticket", method = RequestMethod.POST)
    @ResponseBody
    public String Validate(String code,String teamId,String activityId) throws JsonProcessingException {
        boolean flag = false;
        if ("111111".equals(code)) {
            this.teamService.ticketSuccess(teamId,activityId);
            flag = true;
        }
        if (flag) {
            return ServerResponse.okToJsonString("success");
        } else {
            return ServerResponse.okToJsonString("failed");
        }
    }


    /**
     * 返回需要跳转的成功页面
     *
     * @param request  request
     * @param response response
     * @return ModelAndView
     */
    @RequestMapping(value = "/validate_success", method = RequestMethod.GET)
    public ModelAndView validateSuccess(HttpServletRequest request, HttpServletResponse response, String activityId) {
        ModelAndView mv = new CModelAndView("/warrior/activity/apply_success", request, response);
        String userId = (String) request.getSession().getAttribute("userId");
        UserEntity userEntity = this.userService.findUserById(userId);
        mv.addObject("userEntity", userEntity);
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        mv.addObject("activityEntity", activityEntity);
        return mv;
    }


    /**
     * ajax分页
     * @param size 分页大小
     * @param page 当前页
     * @param orderType 排序类型
     * @return json
     */
    @RequestMapping(value = "/pageAllActivitySeriesInAjax", method = RequestMethod.POST)
    @ResponseBody
    public String pageAllActivityInAjax(String size, String page, String orderType) {
        //分页系列赛
        Page<ActivityEntity> activityEntities = this.activityService.listActivityByActivityType(CommonUtils.String2Int(size), CommonUtils.String2Int(page), 0, orderType);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString(activityEntities);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }

    /**
     * ajax分页
     * @param size 分页大小
     * @param page 当前页
     * @param orderType 排序类型
     * @return json
     */
    @RequestMapping(value = "/pageAllActivityRankingInAjax", method = RequestMethod.POST)
    @ResponseBody
    public String pageAllActivityRankingInAjax(String size, String page, String orderType) {
        //分页排名赛
        Page<ActivityEntity> activityEntities = this.activityService.listActivityByActivityType(CommonUtils.String2Int(size), CommonUtils.String2Int(page), 1, orderType);
        String returnMap = null;
        try {
            returnMap = ServerResponse.okToJsonString(activityEntities);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return returnMap;
    }


}